/* eslint-disable */
import type { MicroAppStateActions } from 'qiankun'
import { store } from '@/store'
import { MODULE_NAME } from '@/store/modules/App/types'
import { Actions } from './app.constants'

interface IInitGlobalState {
  // eslint-disable-next-line no-unused-vars
  (state?: Record<string, any>): MicroAppStateActions
}

interface IGlobalState {
  action: keyof typeof Actions
  value?: any
}
interface IOnGlobalStateChangeCallbackFn {
  (state: IGlobalState, prevState: IGlobalState): void
}
interface IOnGlobalStateChangeFn {
  (callback: IOnGlobalStateChangeCallbackFn, fireImmediately?: boolean): void
}
interface IOffGlobalStateChangeFn {
  (): boolean
}
interface IDispatchActionFn {
  (state: IGlobalState): boolean
}

const STATE: IGlobalState = {
  action: Actions.EMPTY,
  value: '',
}

let HAS_INIT_ACTION = false
let _onGlobalStateChange: IOnGlobalStateChangeFn
let _dispatchAction: IDispatchActionFn
let _offGlobalStateChange: IOffGlobalStateChangeFn

/**
 * @name 启动qiankun应用间通信机制
 */
export function appAction(initGlobalState: IInitGlobalState) {
  /**
   * @name 初始化数据内容
   */
  const {
    onGlobalStateChange,
    setGlobalState: dispatchAction,
    offGlobalStateChange,
  } = initGlobalState(STATE)
  HAS_INIT_ACTION = true
  _dispatchAction = dispatchAction
  _onGlobalStateChange = onGlobalStateChange as IOnGlobalStateChangeFn
  _offGlobalStateChange = offGlobalStateChange

  /**
   * @name 监听数据变动
   * @param {Function} 监听到数据发生改变后的回调函数
   * @des 将监听到的数据存入vuex
   */
  onGlobalStateChange((curState, prevState) => {
    const { action, value } = curState as IGlobalState
    if (!!action && action !== Actions.EMPTY) {
      // console.log(action)
      // const actionName = `${MODULE_NAME}/${action}`
      // const haveActionInStore = !!(store as AnyObject)?._actions?.[actionName];
      // if (haveActionInStore) {
      //   store.dispatch(actionName, value)
      // }
    }
  })

  return {
    onGlobalStateChange: onGlobalStateChange as any,
    offGlobalStateChange,
    dispatchAction,
  } as {
    onGlobalStateChange: IOnGlobalStateChangeFn
    dispatchAction: IDispatchActionFn
    offGlobalStateChange: IOffGlobalStateChangeFn
  }
}

export const onGlobalStateChange: IOnGlobalStateChangeFn = function (
  callback,
  fireImmediately
) {
  if (!HAS_INIT_ACTION || !_onGlobalStateChange) {
    throw new Error('Not started qiankun!')
  }
  _onGlobalStateChange(callback, fireImmediately)
}

export const offGlobalStateChange: IOffGlobalStateChangeFn = function () {
  if (!HAS_INIT_ACTION || !_offGlobalStateChange) {
    throw new Error('Not started qiankun!')
  }
  return _offGlobalStateChange()
}

/**
 * dispatch Action
 * @param state
 * @returns
 */
export const dispatchAction: IDispatchActionFn = function (state) {
  if (!HAS_INIT_ACTION || !_dispatchAction) {
    throw new Error('Not started qiankun!')
  }
  return _dispatchAction(state)
}
